package com.download;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlTest {

    public static void main(String[] args) throws Exception {
        //下载地址
        URL url = new URL("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farticle%2F768a4bfbf5c492a7651f71fd7d6207ab4c325f34.jpg&refer=http%3A%2F%2Fi0.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1615891395&t=7a30b5d44465989d0c9e161849f7b1ec");
        //连接到这个资源
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        //得到其文件输出流
        InputStream inputStream = urlConnection.getInputStream();

        //输出数据到c.m4a文件,默认根目录为工程目录
        FileOutputStream fos = new FileOutputStream("a.jpg");

        byte[] buffer = new byte[1024];
        int len;
        while(-1 != (len=inputStream.read(buffer))){
            //边读边写到文件输出流
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();
    }

}
